package com.atguigu.multiReading;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;

class MyTask implements Comparable<MyTask>{
    private Runnable runnable;
    private long time;
    public MyTask(Runnable runnable,long time){
        this.runnable=runnable;
        this.time=System.currentTimeMillis()+time;
    }

    public Runnable getRunnable() {
        return runnable;
    }

    public long getTime() {
        return time;
    }
    public int compareTo(MyTask o){
        return (int)(this.time-o.time);
    }
}
class MyTimer{
    private BlockingQueue<MyTask> queue=new PriorityBlockingQueue<>();
    private  Object locker=new Object();
    public MyTimer(){
        //创建一个扫描线程
        Thread thread=new Thread(()->{
            while(true){
                 //取出队首元素
                try {
                    MyTask task=queue.take();
                    long curTime=System.currentTimeMillis();
                    if(System.currentTimeMillis()>=task.getTime()){
                        //到点了
                        task.getRunnable().run();
                    }else {
                        queue.put(task);
                        //没到点就等待
                        synchronized (locker) {
                            locker.wait(task.getTime() - curTime);
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();
    }
    public void schedule(Runnable runnable,long time) throws InterruptedException {
        MyTask myTask=new MyTask(runnable,time);
        queue.put(myTask);
        synchronized (locker){
            locker.notify();
        }
    }
}
public class demo4 {
    public static void main(String[] args) throws InterruptedException {
        MyTimer myTimer=new MyTimer();
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("时间到了");
            }
        },3000);
        System.out.println("开始计时");
    }
}
